#!/usr/bin/ksh
#
# description: gmetad startup script
#
# Oct 27, 2010, Michael Perzl (michael@perzl.org)
#

GMETAD_BIN=/opt/freeware/sbin/gmetad

PIDFILE=/var/run/gmetad.pid

RUN_AS_USER="nobody"


# define some generic commands
AWK=/usr/bin/awk
CAT=/usr/bin/cat
ECHO=/usr/bin/echo
GREP=/usr/bin/grep
KILL=/usr/bin/kill
MKDIR=/usr/bin/mkdir
PRINTF=/usr/bin/printf
PS=/usr/bin/ps
RM=/usr/bin/rm


# check for missing binaries (stale symlinks should not happen)
test -x ${GMETAD_BIN} ||
    {
      $ECHO "${GMETAD_BIN} not installed"
      if [ "$1" = "stop" ] ; then
          exit 0
      else
          exit 5
      fi
    }

# check for existence of necessary config file
GMETAD_CONFIG=/etc/ganglia/gmetad.conf
test -r ${GMETAD_CONFIG} ||
    {
      $ECHO "${GMETAD_CONFIG} does not exist"
      if [ "$1" = "stop" ] ; then
          exit 0
      else
          exit 6
      fi
    }


case "$1" in
    start)
	if [ -r ${PIDFILE} ]; then
            pid=`$CAT ${PIDFILE}`
            if [ "`$PS -ef | $GREP -v grep | $GREP ${pid} | $AWK '{ print $2 }'`" = "${pid}" ] ; then
	        $ECHO "GANGLIA gmetad daemon is already running with PID ${pid}."
	        exit 1
	    else
	        $RM -f ${PIDFILE}
	    fi
	fi
	$PRINTF "Starting GANGLIA gmetad... "

	## start daemon and write PID to file ${PIDFILE}
	$MKDIR -p /var/run
	${GMETAD_BIN} -p ${PIDFILE} -c ${GMETAD_CONFIG}
        $ECHO "done."
	;;
    stop)
	$PRINTF "Shutting down GANGLIA gmetad daemon... "
	## stop daemon
	if [ -r ${PIDFILE} ]; then
	    $KILL -HUP `$CAT ${PIDFILE}`
	    $RM -f ${PIDFILE}
	fi
        $ECHO "done."
	;;
    status)
	if [ -r ${PIDFILE} ]; then
            pid=`$CAT ${PIDFILE}`
            if [ `$PS -ef | $GREP -v grep | $GREP ${pid} | $AWK '{ print $2 }'` = ${pid} ] ; then
	        $ECHO "GANGLIA gmetad daemon is running with PID ${pid}."
	    fi
	else
	    $ECHO "GANGLIA gmetad daemon is not running."
	fi
	;;
    restart)
	## Stop the service and regardless of whether it was
	## running or not, start it again.
	$0 stop
	$0 start
	;;
    *)
	$ECHO "Usage: $0 {start|stop|status|restart}"
	exit 1
	;;
esac

